﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ToDoList.Entity.Models;

namespace ToDoList.Logic
{
    //清单的功能
    public class InventoryFunction
    {
        private static TodoContext _ctx = new TodoContext();
   
        /// <summary>
        /// 查看所有的清单
        /// </summary>
        /// <returns></returns>
        public List<Inventory> GetAllInventory(int userId)
        {
            return  _ctx.Inventory.Where (p => p.UserId == userId).ToList();
        }
        /// <summary>
        ///修改清单名 
        /// </summary>
        /// <param name="listId"></param>
        /// <param name="changeName"></param>
        /// <returns></returns>
        public bool ModifyInventoryName(int userId, int listId, string changeName)
        {
            var result = FindInventory(userId, listId);
            if (result != null)
            {
                result.Name = changeName;
                _ctx.SaveChanges();
                return true;
            }
                return false;
        }
        /// <summary>
        ///创建清单,输入新建清单的ID号，清单的名称。创建成功返回true
        /// </summary>
        /// <param name="user"></param>
        /// <param name="listID"></param>
        /// <param name="title"></param>
        /// <param name="overTime"></param>
        /// <returns></returns>
        public void  AddInventory(int userId, string title)
        {
                Inventory addList = new Inventory
                {
                    CreationTime = DateTime.Now,
                    Name  = title,
                    UserId = userId,
                };
                _ctx.Inventory.Add(addList);
                _ctx.SaveChanges();

        }
        /// <summary>
        /// 删除清单
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="listId"></param>
        public void DeleteInventory(int userId, int listId)
        {
            var inventory = FindInventory(userId,listId );
            foreach(var item in inventory.Matters)
            {
                inventory.Matters.Remove(item);
            }
            _ctx.Inventory.Remove(inventory);
            _ctx.SaveChanges();
        }
        /// <summary>
        /// 寻找清单
        /// </summary>
        /// <param name="listID"></param>
        /// <returns></returns>
        public Inventory FindInventory(int userId, int listID)
        {
            return _ctx.Inventory.SingleOrDefault(prop => prop.Id  == listID && prop.UserId == userId);

        }
    }
}
